<template>
  <div class="appointment-container">
    <div class="page-header">
      <h1 class="page-title">
        <el-icon class="title-icon"><Calendar /></el-icon>
        我的预约
      </h1>
      <p class="page-subtitle">管理您的技能交流预约</p>
    </div>

    <div class="content">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="我发起的" name="requests">
          <div class="appointment-list" v-loading="loading">
            <el-empty v-if="appointments.length === 0" description="暂无数据" />
            <div v-for="item in appointments" :key="item.id" class="appointment-card">
              <div class="card-header">
                <h3>{{ item.skillTitle }}</h3>
                <el-tag :type="getStatusType(item.status)">{{ item.statusText }}</el-tag>
              </div>
              <div class="card-body">
                <div class="info-row">
                  <span class="label">提供者：</span>
                  <div class="user">
                    <el-avatar :size="24" :src="item.providerAvatar">{{ item.providerNickname?.[0] }}</el-avatar>
                    <span>{{ item.providerNickname }}</span>
                  </div>
                </div>
                <div class="info-row">
                  <span class="label">预约时间：</span>
                  <span>{{ formatTime(item.appointmentTime) }}</span>
                </div>
                <div class="info-row">
                  <span class="label">时长：</span>
                  <span>{{ item.duration }} 分钟</span>
                </div>
                <div class="info-row" v-if="item.note">
                  <span class="label">备注：</span>
                  <span>{{ item.note }}</span>
                </div>
              </div>
              <div class="card-footer">
                <el-button v-if="item.status === 1" size="small" type="success" @click="startAppointment(item.id)">
                  开始
                </el-button>
                <el-button v-if="item.status === 2" size="small" type="primary" @click="completeAppointment(item.id)">
                  完成
                </el-button>
                <el-button v-if="item.status === 3 && !item.hasReviewed" size="small" type="warning" @click="showReviewDialog(item)">
                  评价
                </el-button>
                <el-button v-if="item.status < 3" size="small" type="danger" @click="cancelAppointment(item.id)">
                  取消
                </el-button>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="我收到的" name="received">
          <div class="appointment-list" v-loading="loading">
            <el-empty v-if="appointments.length === 0" description="暂无数据" />
            <div v-for="item in appointments" :key="item.id" class="appointment-card">
              <div class="card-header">
                <h3>{{ item.skillTitle }}</h3>
                <el-tag :type="getStatusType(item.status)">{{ item.statusText }}</el-tag>
              </div>
              <div class="card-body">
                <div class="info-row">
                  <span class="label">发起者：</span>
                  <div class="user">
                    <el-avatar :size="24" :src="item.requesterAvatar">{{ item.requesterNickname?.[0] }}</el-avatar>
                    <span>{{ item.requesterNickname }}</span>
                  </div>
                </div>
                <div class="info-row">
                  <span class="label">预约时间：</span>
                  <span>{{ formatTime(item.appointmentTime) }}</span>
                </div>
                <div class="info-row">
                  <span class="label">时长：</span>
                  <span>{{ item.duration }} 分钟</span>
                </div>
                <div class="info-row" v-if="item.note">
                  <span class="label">备注：</span>
                  <span>{{ item.note }}</span>
                </div>
              </div>
              <div class="card-footer">
                <el-button size="small" @click="viewDetail(item.id)">
                  <el-icon><View /></el-icon>
                  查看详情
                </el-button>
                <el-button v-if="item.status === 0" size="small" type="success" @click="confirmAppointment(item.id)">
                  确认
                </el-button>
                <el-button v-if="item.status === 0" size="small" type="danger" @click="rejectAppointment(item.id)">
                  拒绝
                </el-button>
                <el-button v-if="item.status === 1" size="small" type="success" @click="startAppointment(item.id)">
                  开始
                </el-button>
                <el-button v-if="item.status === 2" size="small" type="primary" @click="completeAppointment(item.id)">
                  完成
                </el-button>
                <el-button v-if="item.status === 3 && !item.hasReviewed" size="small" type="warning" @click="showReviewDialog(item)">
                  评价
                </el-button>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 评价对话框 -->
    <ReviewDialog
      v-model:visible="reviewDialogVisible"
      :appointment-id="currentAppointment?.id"
      :reviewee-id="currentAppointment?.revieweeId"
      @success="handleReviewSuccess"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { View, Calendar } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import {
  getMyRequests,
  getMyReceived,
  confirmAppointment as confirmApi,
  rejectAppointment as rejectApi,
  cancelAppointment as cancelApi,
  startAppointment as startApi,
  completeAppointment as completeApi
} from '@/api/appointment'
import ReviewDialog from '@/components/ReviewDialog.vue'

const router = useRouter()
const loading = ref(false)
const activeTab = ref('requests')
const appointments = ref([])
const reviewDialogVisible = ref(false)
const currentAppointment = ref(null)

const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const getStatusType = (status) => {
  const types = ['info', 'success', 'warning', 'success', 'danger', 'danger']
  return types[status] || 'info'
}

const fetchAppointments = async () => {
  loading.value = true
  try {
    const api = activeTab.value === 'requests' ? getMyRequests : getMyReceived
    const res = await api({ page: 1, size: 100 })
    appointments.value = res.data.records || []
  } catch (error) {
    console.error('获取预约列表失败：', error)
  } finally {
    loading.value = false
  }
}

const handleTabChange = () => {
  fetchAppointments()
}

const confirmAppointment = async (id) => {
  try {
    await confirmApi(id)
    ElMessage.success('已确认预约')
    fetchAppointments()
  } catch (error) {
    console.error('确认失败：', error)
  }
}

const rejectAppointment = async (id) => {
  try {
    await ElMessageBox.confirm('确定要拒绝此预约吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await rejectApi(id)
    ElMessage.success('已拒绝预约')
    fetchAppointments()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('拒绝失败：', error)
    }
  }
}

const cancelAppointment = async (id) => {
  try {
    await ElMessageBox.confirm('确定要取消此预约吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await cancelApi(id)
    ElMessage.success('已取消预约')
    fetchAppointments()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消失败：', error)
    }
  }
}

const startAppointment = async (id) => {
  try {
    await startApi(id)
    ElMessage.success('已开始预约')
    fetchAppointments()
  } catch (error) {
    console.error('开始失败：', error)
  }
}

const completeAppointment = async (id) => {
  try {
    await completeApi(id)
    ElMessage.success('预约已完成')
    fetchAppointments()
  } catch (error) {
    console.error('完成失败：', error)
  }
}

const showReviewDialog = (item) => {
  // 确定被评价者ID（对于发起者，评价的是提供者；对于接收者，评价的是发起者）
  const revieweeId = activeTab.value === 'requests' ? item.providerId : item.requesterId
  
  currentAppointment.value = {
    id: item.id,
    revieweeId: revieweeId
  }
  reviewDialogVisible.value = true
}

const handleReviewSuccess = () => {
  ElMessage.success('感谢您的评价')
  fetchAppointments()
}

const viewDetail = (id) => {
  router.push(`/appointment/detail/${id}`)
}

onMounted(() => {
  fetchAppointments()
})
</script>

<style scoped>
.appointment-container {
  min-height: 100%;
  padding: 30px 20px;
  animation: fadeIn 0.6s ease-out;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 32px;
  font-weight: 800;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.title-icon {
  font-size: 36px;
  color: #667eea;
}

.page-subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.content {
  max-width: 1100px;
  margin: 0 auto;
  background: white;
  padding: 30px;
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.12);
  border: 1px solid rgba(102, 126, 234, 0.1);
}

.content :deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

.content :deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 600;
  padding: 0 24px;
  transition: all 0.3s;
}

.content :deep(.el-tabs__item.is-active) {
  color: #667eea;
}

.content :deep(.el-tabs__active-bar) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  height: 3px;
}

.appointment-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 24px 0;
  min-height: 300px;
}

.appointment-card {
  border: 1px solid rgba(102, 126, 234, 0.15);
  border-radius: 16px;
  padding: 24px;
  transition: all 0.3s;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.02) 0%, rgba(255, 255, 255, 1) 100%);
}

.appointment-card:hover {
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.15);
  transform: translateY(-4px);
  border-color: #667eea;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f2f5;
}

.card-header h3 {
  font-size: 18px;
  font-weight: 700;
  margin: 0;
  color: #333;
}

.card-body {
  margin-bottom: 20px;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 14px;
  font-size: 15px;
}

.label {
  color: #909399;
  width: 100px;
  font-weight: 600;
}

.user {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user .el-avatar {
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

.user span {
  font-weight: 600;
  color: #333;
}

.card-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.card-footer .el-button {
  border-radius: 10px;
  font-weight: 600;
  padding: 10px 20px;
  transition: all 0.3s;
}

.card-footer .el-button--success {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border: none;
}

.card-footer .el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.card-footer .el-button--warning {
  background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%);
  border: none;
}

.card-footer .el-button--danger {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  border: none;
}

.card-footer .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .appointment-container {
    padding: 20px 12px;
  }

  .page-title {
    font-size: 24px;
  }

  .title-icon {
    font-size: 28px;
  }

  .page-subtitle {
    font-size: 14px;
  }

  .content {
    padding: 20px;
    border-radius: 12px;
  }

  .appointment-card {
    padding: 16px;
    border-radius: 12px;
  }

  .card-header h3 {
    font-size: 16px;
  }

  .info-row {
    font-size: 14px;
    flex-wrap: wrap;
  }

  .label {
    width: 80px;
  }

  .card-footer {
    flex-wrap: wrap;
  }

  .card-footer .el-button {
    flex: 1;
    min-width: 80px;
  }
}
</style>

